package com.sj.purchase.modules.gy.service;

import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;

import com.sj.purchase.modules.gy.domain.GySku;
import com.sj.purchase.modules.gy.repository.GySkuRepository;
import com.sj.purchase.modules.gy.repository.GySpuRepository;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.modules.gy.domain.GySpu;
import com.sj.purchase.util.HttpUtil;

/**
 *同步spu信息
 * Created by icodebug on 17-5-25.
 */
@Service
public class GySpuService {
	
	@Autowired
    GySkuRepository gySkuRepository;
	
	@Autowired
    GySpuRepository gySpuRepository;
	public void saveSpu() throws ClientProtocolException, IOException{
		try {
			
			 HttpGet get = HttpUtil.get("http://192.168.2.141:8060/goods/getSpu");
	         CloseableHttpClient httpclient = HttpUtil.httpclient();
	         org.apache.http.HttpResponse response = httpclient.execute(get);
	         String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
	         HttpUtil.close(httpclient);
	         JSONArray spuArr=JSON.parseArray(jsonStr);
	         for(int i =0;i<spuArr.size();i++){
	        	 GySpu spu = new GySpu();
	        	 //spu
	        	 JSONObject object= JSON.parseObject(spuArr.get(i).toString());
	        	 spu.setId(object.get("spuNo")==null?"":object.get("spuNo").toString());
	        	 spu.setName(object.get("spuName")==null?"":object.get("spuName").toString());
	        	 gySpuRepository.save(spu);
	        	 //sku
	        	 if(object.get("sku")!=null){
		        	 JSONArray skuArr = JSON.parseArray(object.get("sku").toString());
		        	 Collection<GySku> gyskus = new HashSet();
		        	 for(int j =0;j<skuArr.size();j++){
		        		 GySku sku = new GySku();
		        		 JSONObject skuObject= JSON.parseObject(skuArr.get(j).toString());
		        		 sku.setId(skuObject.get("skuNo")==null?"":skuObject.get("skuNo").toString());
		        		 sku.setName(skuObject.get("skuName")==null?"":skuObject.get("skuName").toString());
		        		 sku.setGySpu(spu);
		        		 gySkuRepository.save(sku);
		        		 gyskus.add(sku);
		        	 }
	        	 }
	         }
         
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
}
